import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import axios from 'axios'

export default createStore({
  plugins: [
    createPersistedState({
      key: 'library-management',
      paths: ['token', 'user'],
      storage: window.localStorage
    })
  ],
  
  state: {
    token: '',
    user: null
  },
  
  mutations: {
    setToken(state, token) {
      state.token = token
      // 设置axios默认请求头
      if (token) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
      } else {
        delete axios.defaults.headers.common['Authorization']
      }
    },
    
    setUser(state, user) {
      state.user = user
    },
    
    logout(state) {
      state.token = ''
      state.user = null
      delete axios.defaults.headers.common['Authorization']
    }
  },
  
  actions: {
    async getUserInfo({ commit }) {
      try {
        const response = await axios.get('/api/users/me')
        console.log('User info response:', response.data)
        commit('setUser', response.data)
      } catch (error) {
        console.error('Failed to get user info:', error)
        commit('logout')
        throw error
      }
    },

    // 初始化store的action
    async initializeStore({ state, commit, dispatch }) {
      // 如果有token，重新设置axios的Authorization header
      if (state.token) {
        commit('setToken', state.token)
        if (!state.user) {
          try {
            await dispatch('getUserInfo')
          } catch (error) {
            console.error('Failed to restore user session:', error)
          }
        }
      }
    }
  }
}) 